<?php
/**
 * Created by PhpStorm.
 * User: yuyj
 * Date: 16-12-9
 * Time: 下午5:20
 */

namespace common\services\outstock;

use common\services\BaseService;
use common\repositories\outstock\DeliveryOrderRepository;
use common\repositories\outstock\DeliveryProductRepository;
use common\repositories\outstock\DeliverySubOrderRepository;
use common\entities\outstock\MyscrmDeliveryOrderEntity;
use common\support\CacheManage;
use common\repositories\config\ConfigSettingRepository;
use linslin\yii2\curl\Curl;
use common\services\common\MyscrmOrganizationService;
use common\repositories\outstock\DeliveryFlowRecordRepository;
use common\support\StringHelper;
use common\repositories\myhtsq\ErpBusinessUnitRepository;
use common\services\common\MyscrmContractManageService;
use yii\helpers\ArrayHelper;
use common\models\common\ApplicationInfoMappingModel;
use common\services\common\MyscrmAuthorizeService;
use common\repositories\outstock\DeliveryAttachmentRepository;
use common\services\outstock\DeliveryOrderFlowService;
use common\models\common\ErpUserModel;
use common\repositories\common\MyscrmAuthorizeRepository;
use common\services\config\ConfigSettingService;

/**
 * 出库流程
 */
class DeliveryOrderService extends BaseService
{
    use \common\traits\FileLoggerTrait;
    private $_deliveryFlowRecordRepository;
    private $_deliveryOrderRepository;
    public function __construct($config=[],DeliveryOrderRepository $deliveryOrderRepository,DeliveryFlowRecordRepository $deliveryFlowRecordRepository)
    {
        $this->_deliveryFlowRecordRepository = $deliveryFlowRecordRepository;
        $this->_deliveryOrderRepository=$deliveryOrderRepository;
        $logFile=sprintf('%s/logs/stock_out/%s/%s.log', \Yii::$app->getRuntimePath(), date('Ymd'),date('H') );
        $this->enableFileLog($logFile,1);//开启日志
        parent::__construct($config);
    }
    public function saveDeliveryOrder($deliveryOrderDetail){
        /** @var DeliveryOrderRepository $deliveryOrderRepository */
        $deliveryOrderRepository=\Yii::createObject(DeliveryOrderRepository::className());
        /** @var DeliveryProductRepository $deliveryProductRepository */
        $deliveryProductRepository=\Yii::createObject(DeliveryProductRepository::className());
        /** @var DeliverySubOrderRepository $deliverySubOrderRepository */
        $deliverySubOrderRepository=\Yii::createObject(DeliverySubOrderRepository::className());
        /** @var DeliveryAttachmentRepository $deliveryAttachmentRepository */
        $deliveryAttachmentRepository=\Yii::createObject(DeliveryAttachmentRepository::className());
        $this->log('确认出库单，出库信息：'.var_export($deliveryOrderDetail,true));
        $data=[];
        $form=$deliveryOrderDetail['DeliveryForm'];
        $ykInfo=$deliveryOrderDetail['YkInfo'];
        $files=$deliveryOrderDetail['Files'];
        if(!isset($form['Delivery_Scene'])||!isset($form['Delivery_Guid'])){
            return self::setAndReturn(__LINE__,"出库单信息不完整，无法保存出库单信息！");
        }
        $data['delivery_guid']=$form['Delivery_Guid'];
        $findRes=$this->findDeliveryOrderByDeliveryGuid($form['Delivery_Guid']);
        if(!empty($findRes)){
            return self::setAndReturn(__LINE__,"您已经确认过此出库单，请勿重复操作！");
        }
        $data['order_code']=$form['Delivery_Code'];
        if(isset($form['Delivery_Group'])){
            switch ($form['Delivery_Group']){
                case 0:
                    $data['business_pattern']=DeliveryOrderRepository::$businessPatternMap['联营'];
                    break;
                case 1:
                    $data['business_pattern']=DeliveryOrderRepository::$businessPatternMap['直属'];
                    break;
                default:
                    $data['business_pattern']=DeliveryOrderRepository::$businessPatternMap['直属'];

            }
        }else{
            $data['business_pattern']=DeliveryOrderRepository::$businessPatternMap['直属'];
        }
        $data['created_on']=isset($form['Created_On'])?$form['Created_On']:null;
        $data['modified_on']=isset($form['Modify_On'])?$form['Modify_On']:null;
        $data['top_customer_guid']=isset($form['Top_Cst_Guid'])?$form['Top_Cst_Guid']:'';
        $data['top_customer_name']=isset($form['Top_Cst_Shortname'])?$form['Top_Cst_Shortname']:'';
        $data['top_customer_fullname']=isset($form['Top_Cst_Fullname'])?$form['Top_Cst_Fullname']:'';
        $data['deliver_name']=isset($form['Person_Name'])?$form['Person_Name']:'';
        $data['deliver_guid']=isset($form['Person_Id'])?$form['Person_Id']:'';
        $data['delivery_scene']=$form['Delivery_Scene'];
        $data['org_code']=$ykInfo['Enterprise_Code'];
        $data['org_name']=$ykInfo['Enterprise_Name'];
        $data['customer_id']=isset($form['Cst_Guid'])?$form['Cst_Guid']:'';
        $data['customer_full_name']=isset($form['Cst_Fullname'])?$form['Cst_Fullname']:'';
        $data['customer_name']=isset($form['Cst_Shortname'])?$form['Cst_Shortname']:'';
        $data['deliver_buguid']=$form['Buguid'];
        $data['deliver_buname']=$form['BuName'];
        $data['signguid']=$form['Signguid'];
        $data['signno']=$form['Signno'];
        $data['special_type']=$form['Special_Type'];
        $data['promise_fulfil_time']=isset($form['Promise_Date'])?$form['Promise_Date']:null;
        $data['promise_fulfil_principle']=isset($form['Promise_Userguid'])?$form['Promise_Userguid']:'';
        $data['promise_fulfil_name']=isset($form['Promise_Username'])?$form['Promise_Username']:'';
        $data['remark']=$ykInfo['Remark'];
        $data['is_new_org']=(isset($ykInfo['Has_Account'])&&intval($ykInfo['Has_Account'])==1)?0:1;
        $data['sign_people_id']=isset($ykInfo['Sign_User_Guid'])?$ykInfo['Sign_User_Guid']:'';
        $data['sign_people_name']=isset($ykInfo['Sign_User_Name'])?$ykInfo['Sign_User_Name']:'';
        $data['sign_people_tel']=isset($ykInfo['Sign_User_Tel'])?$ykInfo['Sign_User_Tel']:'';
        $data['sign_people_mail']=isset($ykInfo['Sign_User_Mail'])?$ykInfo['Sign_User_Mail']:'';
        $data['adviser_guid']=isset($ykInfo['Adviser_Guid'])?$ykInfo['Adviser_Guid']:'';
        $data['adviser_name']=isset($ykInfo['Adviser_Name'])?$ykInfo['Adviser_Name']:'';
        $data['adviser_tel']=isset($ykInfo['Adviser_Tel'])?$ykInfo['Adviser_Tel']:'';
        $data['adviser_mail']=isset($ykInfo['Adviser_Mail'])?$ykInfo['Adviser_Mail']:'';
        $this->log('确认出库单，转换后的出库信息：'.var_export($data,true));
        $isNewOrg=(isset($data['is_new_org'])&&$data['is_new_org'])?true:false;
        $products=$deliveryOrderDetail['Products'];
        $deliveryContracts=[];
        $deliveryProducts=[];
        if(!$isNewOrg){
            //已有帐号
            if(empty($data['org_code'])){
                $this->log('确认出库单，出库单缺少企业号信息');
                return self::setAndReturn(__LINE__,"出库单缺少企业号信息");
            }
            /** @var MyscrmOrganizationService $organizationService */
            $organizationService=\Yii::createObject(MyscrmOrganizationService::className());
            $org=$organizationService->getOrgByUniqueName($data['org_code']);
            if(empty($org)){
                $this->log('确认出库单，无法获取出库单帐号信息');
                return self::setAndReturn(__LINE__,"无法获取出库单帐号信息");
            }
            $data['org_name']=$org->FriendlyName;
            $data['org_id']=$org->Id;
        }else{
            //未开通帐号
            if(empty($data['org_name'])){
                $this->log('确认出库单，出库单缺少企业名称');
                return self::setAndReturn(__LINE__,"出库单缺少企业名称");
            }
        }
        if($form['Delivery_Scene']==DeliveryOrderRepository::$deliverySceneMap['特批']){
            switch ($data['special_type']){
                case '合同未归档款项未回':
                    $data['special_type']=10;
                    break;
                case '合同已归档款项未回':
                    $data['special_type']=20;
                    break;
                default:
                    $data['special_type']=30;
                    break;
            }
        }
        if($form['Delivery_Scene']==DeliveryOrderRepository::$deliverySceneMap['特批']&&$data['special_type']!=20){
            $subOrderId = StringHelper::uuid();
            $deliveryContracts[] = [
                'sub_order_id' => $subOrderId,
                'erp_contract_id' => '',
                'erp_contract_code' => '',
                'delivery_guid' => $form['Delivery_Guid'],
                'sub_order_index' => 1,
                'sub_order_code' => 'S'.date('YmdHis',time()).rand(10000,99999),
                'org_code'=>$isNewOrg?$data['org_org']:'',
                'flow_status'=>$isNewOrg?DeliveryOrderRepository::STATUS_YQR:DeliveryOrderRepository::STATUS_YKT
            ];
            foreach ($products as $product){
                $tmpProduct=[];
                $tmpProduct['sub_order_id']=$subOrderId;
                $tmpProduct['delivery_guid']=$form['Delivery_Guid'];
                $tmpProduct['application_id']=$product['Product_Info_Id'];
                $tmpProduct['application_name']=$product['Product_Name'];
                $tmpProduct['rent_period']=$product['Rent_Time'];
                $tmpProduct['apply_num']=$product['Quantity'];
                if(!empty($product['CloudSignType'])&&isset(DeliveryProductRepository::$strToSignTypeMap[$product['CloudSignType']])){
                    $tmpProduct['contract_type']=DeliveryProductRepository::$strToSignTypeMap[$product['CloudSignType']];
                }
                $tmpProduct['project_guid']=$product['Project_Guid'];
                $tmpProduct['project_name']=$product['Project_Name'];
                $tmpProduct['rent_start_date']=$product['Rent_Startdate'];
                $tmpProduct['contract_application_id']=$product['Product_Id'];
                $tmpProduct['licensing_standards']=$product['Licensing_Standards'];
                $tmpProduct['settlement_amount']=$product['Settlement_Amount'];
                $tmpProduct['remarks']=$product['Remark'];
                $deliveryProducts[]=$tmpProduct;
            }
        }else{
            $subOrderIndex=0;
            foreach ($products as $product) {
                if (isset($product['Signguid']) && !empty($product['Signguid'])) {
                    //没有创建待办的合同则创建一个新的待办
                    if(!isset($deliveryContracts[$product['Signguid']])){
                        $subOrderIndex=$subOrderIndex+1;
                        $subOrderId = StringHelper::uuid();
                        $deliveryContracts[$product['Signguid']] = [
                            'sub_order_id' => $subOrderId,
                            'erp_contract_id' => $product['Signguid'],
                            'erp_contract_code' => $product['Signno'],
                            'delivery_guid' => $form['Delivery_Guid'],
                            'sub_order_index' => $subOrderIndex,
                            'sub_order_code' => 'S'.date('YmdHis',time()).rand(10000,99999),
                            'org_code'=>$isNewOrg?$data['org_code']:'',
                            'flow_status'=>$isNewOrg?DeliveryOrderRepository::STATUS_YQR:DeliveryOrderRepository::STATUS_YKT
                        ];
                    }
                }else{
                    $this->log('确认出库单，部分产品缺少关联合同号或者会签号');
                    return self::setAndReturn(__LINE__,"部分产品缺少关联合同号或者会签号！");
                }
            }
            foreach ($products as $product){
                $tmpProduct=[];
                $tmpProduct['sub_order_id']=$deliveryContracts[$product['Signguid']]['sub_order_id'];
                $tmpProduct['delivery_guid']=$form['Delivery_Guid'];
                $tmpProduct['application_id']=$product['Product_Info_Id'];
                $tmpProduct['application_name']=$product['Product_Name'];
                $tmpProduct['rent_period']=$product['Rent_Time'];
                $tmpProduct['apply_num']=$product['Quantity'];
                if(!empty($product['CloudSignType'])&&isset(DeliveryProductRepository::$strToSignTypeMap[$product['CloudSignType']])){
                    $tmpProduct['contract_type']=DeliveryProductRepository::$strToSignTypeMap[$product['CloudSignType']];
                }
                $tmpProduct['project_guid']=$product['Project_Guid'];
                $tmpProduct['project_name']=$product['Project_Name'];
                $tmpProduct['rent_start_date']=$product['Rent_Startdate'];
                $tmpProduct['contract_application_id']=$product['Product_Id'];
                $tmpProduct['licensing_standards']=$product['Licensing_Standards'];
                $tmpProduct['settlement_amount']=$product['Settlement_Amount'];
                $deliveryProducts[]=$tmpProduct;
            }
        }
        $deliveryAttachments=[];
        foreach ($files as $file){
            $attachment=[];
            $attachment['delivery_guid']=$data['delivery_guid'];
            $attachment['file_guid']=$file['FileGUID'];
            $attachment['path']=$file['NetWorkUrl'];
            $attachment['filename']=$file['FileName'];
            $attachment['created_on']=$file['CreateTime'];
            $attachment['created_by']=$file['CreatorGUID'];
            $attachment['file_size']=$file['FileSize'];
            $deliveryAttachments[]=$attachment;
        }
        $conn=MyscrmDeliveryOrderEntity::getDb();
        $transaction=$conn->beginTransaction();
        try {
            foreach ($deliveryContracts as $contract) {
                $addResult = $deliverySubOrderRepository->addContract($contract);
                if ($addResult === false) {
                    $transaction->rollBack();
                    $this->log("添加出库合同失败:". $deliveryOrderRepository->getErrMsg());
                    return self::setAndReturn(__LINE__, "添加出库合同失败:". $deliveryOrderRepository->getErrMsg());
                }
            }
            foreach ($deliveryProducts as $product) {
                $addResult = $deliveryProductRepository->addProduct($product);
                if ($addResult === false) {
                    $transaction->rollBack();
                    $this->log("添加出库产品失败:". $deliveryOrderRepository->getErrMsg());
                    return self::setAndReturn(__LINE__, "添加出库产品失败:". $deliveryOrderRepository->getErrMsg());
                }
            }
            foreach ($deliveryAttachments as $attachment){
                $addResult =$deliveryAttachmentRepository->addFile($attachment);
                if ($addResult === false) {
                    $transaction->rollBack();
                    $this->log("添加出库产品失败:". $deliveryOrderRepository->getErrMsg());
                    return self::setAndReturn(__LINE__, "添加出库产品失败:". $deliveryOrderRepository->getErrMsg());
                }
            }
            $addResult = $deliveryOrderRepository->addDeliveryOrder($data);
            if ($addResult === false) {
                $transaction->rollBack();
                $this->log("添加出库单信息失败:" . $deliveryOrderRepository->getErrMsg());
                return self::setAndReturn(__LINE__, "添加出库单信息失败:" . $deliveryOrderRepository->getErrMsg());
            }
        }catch (\Exception $e){
            $transaction->rollBack();
            \Yii::error($e->getMessage());
            $this->log("添加出库单信息失败:" . (String)$e);
            return self::setAndReturn(__LINE__, "添加出库单信息失败:数据写入发生错误！");
        }
        $transaction->commit();
        return $data;
    }
    private function emailTo($to, $subject, $body)
    {
        \Yii::$app->mailer->messageConfig['from'] = ['yunkeadmin@mysoft.com.cn' => 'hetong-yunke@mingyuanyun.com'];

        return \common\support\EmailHelper::send($to, $subject, $body);
    }
    public function getDeliveryOrderList($page,$pageSize,$type,$step,$keyword=''){
        /** @var ConfigSettingService $configSettingService */
        $configSettingService = \Yii::createObject(ConfigSettingService::className());
        $outStockConfig=$configSettingService->getCacheValue('OUT_STOCK_API_CONFIG',true);
        $deliveryStatus='10,20,21,22';
        if($step){
            switch ($step){
                case 10:
                    $deliveryStatus='10';
                    break;
                case 20:
                    $deliveryStatus='20';
                    break;
                case 30:
                    $deliveryStatus='21,22';
                    break;
                default:
                    $deliveryStatus='10,20,21,22';
            }
        }
        $params=[
            'page'=>$page,
            'page_size'=>$pageSize,
            'platform'=>'yunke',
            'delivery_status'=>$deliveryStatus,
            'keyword'=>$keyword?$keyword:''
        ];
        switch ($type){
            case DeliveryOrderRepository::$deliverySceneMap['正式产品']:
                $params['delivery_scene']='正式产品';
                break;
            case DeliveryOrderRepository::$deliverySceneMap['特批']:
                $params['delivery_scene']='特批产品';
                break;
            default:
                break;
        }
        $curlRes=$this->_curlRequest('get',$outStockConfig['list_api'], $params);
        if ($curlRes===false) {
            return $curlRes;
        }
        $returnData=$curlRes;
        $list=!empty($returnData['rows'])?$returnData['rows']:[];
        $orgCodeArr=[];
        foreach ($list as $key=>$value){
           if(!empty($value['org'])){
               $orgCodeArr[]=$value['org'];
           }
        }
        foreach ($list as $key=>$value){
            $list[$key]=$this->_convertDeliveryOrderListData($value,$outStockConfig['detail_url'],$outStockConfig['tepi_start_url']);
        }
        return ['data'=>$list,'total'=>$returnData['total']];
    }
    private function _convertDeliveryOrderListData($value,$deliveryOrderDetailUrl,$tepiStartUrl){
        $orgStr=(isset($value['org'])?$value['org'].'-':'');
        $deliver_buname=isset($value['buname'])?$value['buname']:'';
        $value['delivery_order_name']=$deliver_buname.'-'.$value['deliver_name'].'-出库申请-'.$orgStr.$value['order_code'];
        $value['delivery_detail_url']=str_replace('${deliveryGuid}',$value['delivery_guid'],$deliveryOrderDetailUrl);
        if($value['delivery_scene']=='正式产品'){
            $value['delivery_type']='正常';
            $value['tepi_start_url']='';
            if($value['delivery_status']<=DeliveryOrderRepository::STATUS_YSP){
                $value['approver']='财务人员';
            }else{
                $value['approver']='';
            }
            if($value['delivery_status']>DeliveryOrderRepository::STATUS_YSP){
                $value['current_step']='已确认';
            }else if($value['delivery_status']==DeliveryOrderRepository::STATUS_YDH){
                $value['current_step']='已打回';
            }else{
                $value['current_step']='财务复核';
            }
        }else if($value['delivery_scene']=='特批产品'){
            $value['delivery_type']='特批';
            $value['approver']='';
            $value['tepi_start_url']=str_replace('${deliveryGuid}',$value['delivery_guid'],$tepiStartUrl);
            if($value['delivery_status']==DeliveryOrderRepository::STATUS_YDH){
                $value['current_step']='已打回';
            }else if(intval($value['delivery_status'])==DeliveryOrderRepository::STATUS_YSP){
                //没有确认的特批才会检查特派状态
                $tepiStatus=$this->_checkTepiIsComplete($value['delivery_guid']);
                if($tepiStatus==30){
                    $value['current_step']='财务复核';
                }else if($tepiStatus==10 ||$tepiStatus==20){
                    $value['current_step']='发起中';
                }else{
                    $value['current_step']='未发起';
                }
            }else{
                $value['current_step']='已确认';
            }
        }
        return $value;
    }
    public function getDeliveryTodoList($page,$pageSize,$type,$status,$keyword,$timeQuantum){
        /** @var DeliverySubOrderRepository $deliverySubOrderRepository */
        $deliverySubOrderRepository=\Yii::createObject(DeliverySubOrderRepository::className());
        $data=$deliverySubOrderRepository->getTodoList($page,$pageSize,$type,$status,$keyword,$timeQuantum);
        return ['data'=>$this->_converTodoData($data['data']),'total'=>$data['total']];
    }
    private function _converTodoData($data){
        if(empty($data)){
            return $data;
        }
        foreach ($data as $key=>$order){
            $data[$key]['id']=$order['sub_order_id'];
            $data[$key]['order_code']=$order['sub_order_code'];
            if($order['delivery_scene']==DeliveryOrderRepository::$deliverySceneMap['正式产品']){
                $data[$key]['delivery_type']='正常';
            }else if($order['delivery_scene']==DeliveryOrderRepository::$deliverySceneMap['特批']){
                $data[$key]['delivery_type']='特批';
            }
            $subOrderIndex=($order['sub_order_index']>9?$order['sub_order_index']:'0'.$order['sub_order_index']);
            $data[$key]['name']=$order['deliver_buname'].'-'.$order['deliver_name'].'-出库申请-'.$order['org_name'].'-'.$order['order_code'].'-'.$subOrderIndex;
            $data[$key]["current_step"] = DeliveryOrderRepository::$statusMap[$order["flow_status"]];
        }
        return $data;
    }
    private function _converDoneData($data){
        if(empty($data)){
            return $data;
        }
        $subOrderIdArr=[];
        foreach ($data as $key=>$order) {
            $subOrderIdArr[]=$order['sub_order_id'];
        }
        $ktFlowDataArr=[];
        if(!empty($subOrderIdArr)) {
            /** @var DeliveryFlowRecordRepository $deliveryFlowRecordRepository */
            $deliveryFlowRecordRepository = \Yii::createObject(DeliveryFlowRecordRepository::className());
            $flowDataRes=$deliveryFlowRecordRepository->getFlowRecordsBySubOrderIds($subOrderIdArr, DeliveryOrderFlowService::ACTION_SQ, 'sub_order_id,created_on');
            foreach ($flowDataRes as $flow){
                $ktFlowDataArr[$flow['sub_order_id']]=$flow;
            }
        }
        foreach ($data as $key=>$order){
            $data[$key]['id']=$order['sub_order_id'];
            $data[$key]['order_code']=$order['sub_order_code'];
            $data[$key]['empowerment_time']=isset($ktFlowDataArr[$order['sub_order_id']])?$ktFlowDataArr[$order['sub_order_id']]['created_on']:'';
            if($order['delivery_scene']==DeliveryOrderRepository::$deliverySceneMap['正式产品']){
                $data[$key]['delivery_type']='正常';
            }else if($order['delivery_scene']==DeliveryOrderRepository::$deliverySceneMap['特批']){
                $data[$key]['delivery_type']='特批';
            }
            $subOrderIndex=($order['sub_order_index']>9?$order['sub_order_index']:'0'.$order['sub_order_index']);
            $data[$key]['name']=$order['deliver_buname'].'-'.$order['deliver_name'].'-出库申请-'.$order['org_name'].'-'.$order['order_code'].'-'.$subOrderIndex;
            $data[$key]["current_step"] = DeliveryOrderRepository::$statusMap[$order["flow_status"]];
        }
        return $data;
    }
    public function getDeliveryDoneList($page,$pageSize,$type,$keyword,$timeQuantum){
        /** @var DeliverySubOrderRepository $deliverySubOrderRepository */
        $deliverySubOrderRepository=\Yii::createObject(DeliverySubOrderRepository::className());
        $data=$deliverySubOrderRepository->getDoneList($page,$pageSize,$type,$keyword,$timeQuantum);
        return ['data'=>$this->_converDoneData($data['data']),'total'=>$data['total']];
    }
    private function _checkTepiIsComplete($deliveryGuid){
        $status=0;
        /** @var ConfigSettingService $configSettingService */
        $configSettingService = \Yii::createObject(ConfigSettingService::className());
        $outStockConfig=$configSettingService->getCacheValue('OUT_STOCK_API_CONFIG',true);
        $params=['delivery_guid'=>$deliveryGuid];
        $curlRes=$this->_curlRequest('get',$outStockConfig['check_tepi_status_api'], $params);
        $this->log('获取特批出库申请状态，deliveryGuid:'.$deliveryGuid.'，返回信息：'.var_export($curlRes,true));
        if($curlRes===false){
            //忽略错误，重置错误信息
            self::setAndReturn(0, '');
            return $status;
        }
        $data=$curlRes;
        $allProcess=[];
        if(!empty($data)){
            foreach ($data as $process){
                if(($process['businessType']=='特批产品')&&($process['businessGUID']==$deliveryGuid)){
                    $processNameArr=explode('-',$process['processName']);
                    $index=$processNameArr[count($processNameArr)-2].$processNameArr[count($processNameArr)-1];
                    $allProcess[$index]=$process;
                }
            }
            if(!empty($allProcess)){
                ksort($allProcess);
                $useProcess=array_pop($allProcess);
                switch ($useProcess['processStatus']){
                    case '发起':
                        $status=10;
                        break;
                    case '审批中':
                        $status=20;
                        break;
                    case '已归档':
                        $status=30;
                        break;
                    default:
                        $status=0;
                }
            }
        }
        return $status;
    }
    private function _curlRequest($method,$url,$params){
        $curl = new Curl();
        $curl->setOption(CURLOPT_CONNECTTIMEOUT,60);
        $curl->setOption(CURLOPT_TIMEOUT,60);
        try{
            if($method=='get'){
                $res = $curl->get($this->_getUrlWithParams($url,$params), true);
            }else{
                $header[] = 'Content-Type:application/x-www-form-urlencoded';
                $curl->setOption(CURLOPT_HTTPHEADER,$header);
                $curl->setOption(CURLOPT_POST,1);
                $postDataStr='';
                foreach ($params as $pkey=>$pvalue){
                    $postDataStr.=$pkey.'='.urlencode($pvalue).'&';
                }
                $postDataStr=trim($postDataStr,'&');
                $curl->setOption(CURLOPT_POSTFIELDS,$postDataStr);
                $res = $curl->post($this->_getUrlWithParams($url), true);
            }
        }catch (\Exception $e){
            $errCode=$e->getCode();
            if($errCode==CURLE_OPERATION_TIMEDOUT||$errCode==CURLE_OPERATION_TIMEOUTED) {
                return self::setAndReturn(__LINE__, '请求远程接口超时,请稍后再试！');
            }else{
                return self::setAndReturn(__LINE__, $e->getMessage());
            }
        }
        $res = json_decode($res, true);
        if ($res && isset($res['userData']['success']) && ($res['userData']['success'] === true)) {
            return $res['userData']['data'];
        }
        $errMsg=isset($res['userData']['message'])&&!empty($res['userData']['message'])?$res['userData']['message']:'远程接口返回数据解析失败！';
        return self::setAndReturn(__LINE__, $errMsg);
    }
    private function _getUrlWithParams($url,$params=[]){
        if(empty($params)){
            return $url;
        }
        if (strpos($url, '?') !== false) {
            $url = $url . '&';
        } else {
            $url = $url . '?';
        }
        $queryString='';
        foreach ($params as $key=>$value){
            $queryString.='&'.$key.'='.urlencode($value);
        }
        return $url.trim($queryString,'&');
    }
    public function delDeliveryOrderByDeliveryGuid($deliveryGuid,$delSubOrderAndProduct=false){
        return $this->_deliveryOrderRepository->delDeliveryOrderByDeliveryGuid($deliveryGuid,$delSubOrderAndProduct);
    }
    public function findDeliveryOrderByDeliveryGuid($deliveryGuid){
        return $this->_deliveryOrderRepository->findDeliveryOrderByDeliveryGuid($deliveryGuid);
    }
    public function subOrderView($subOrderId)
    {
        /** @var DeliverySubOrderRepository $deliverySubOrderRepository */
        $deliverySubOrderRepository=\Yii::createObject(DeliverySubOrderRepository::className());
        /** @var DeliveryAttachmentRepository $deliveryAttachmentRepository */
        $deliveryAttachmentRepository=\Yii::createObject(DeliveryAttachmentRepository::className());
        $subOrder=$deliverySubOrderRepository->findDetailBySubOrderId($subOrderId);
        if(empty($subOrder)){
            return self::setAndReturn(__LINE__,'无法获取待办信息!');
        }
        //获取进货合同信息
        $contract=null;
        if(!empty($subOrder['erp_contract_id'])) {
            if ($subOrder['business_pattern'] == DeliveryOrderRepository::$businessPatternMap['联营']) {
                $contract = $this->_getContractBySignNumber($subOrder['erp_contract_code']);
            } else {
                $contract = $this->_getContractByContractIdOrErpContractId($subOrder['erp_contract_id']);
            }
        }
        if($contract) {
            $subOrder['contract_id'] = $contract->contract_id;
            $subOrder['contract_code'] = $contract->contract_code;
        }else{
            $subOrder['contract_id'] = '';
            $subOrder['contract_code'] = '';
        }
        $subOrder=$this->_covertSubOrderViewData($subOrder);
        if($subOrder['contract_code']) {
            $areaId = $this->_getContractManageAreaIdByContractCode($subOrder['contract_code']);
            $areaName = $this->_getAreaNameByAreaId($areaId);
            $subOrder['areaId'] = $areaId;
            $subOrder['areaName'] = $areaName;
        }
        $products=$this->getProducts($subOrderId);
        $attachments = $deliveryAttachmentRepository->getByDeliveryGuid($subOrder['delivery_guid']);
        return [
            'order'       => $subOrder,
            'products'    => $products,
            'attachments' => $attachments,
        ];
    }
    private function _covertSubOrderViewData($subOrder)
    {
        $subOrder['deliver_user_name']=$subOrder['deliver_name'];
        $subOrder['deliver_user_id']=$subOrder['deliver_guid'];
        $subOrder['order_code']=$subOrder['sub_order_code'];
        if($subOrder['delivery_scene']==1){
            $subOrder['contract_status']=1;
            $subOrder['money_status']=1;
        }else{
            if($subOrder['special_type']==20){
                $subOrder['contract_status']=1;
                $subOrder['money_status']=0;
            }else if($subOrder['special_type']==30){
                $subOrder['contract_status']=0;
                $subOrder['money_status']=1;
            }else{
                $subOrder['contract_status']=0;
                $subOrder['money_status']=0;
            }
        }
        return $subOrder;
    }
    public function getProducts($subOrderId){
        /** @var DeliveryProductRepository $deliveryProductRepository */
        $deliveryProductRepository=\Yii::createObject(DeliveryProductRepository::className());
        $products = $deliveryProductRepository->findProductsBySubOrderId($subOrderId);
        foreach ($products as $key=>$product){
            $products[$key]=$this->_covertProductViewData($product);
        }
        return $products;
    }
    private function _covertProductViewData($product)
    {
        if($product['rent_start_date']){
            $product['rent_start_date']=date('Y-m-d',strtotime($product['rent_start_date']));
        }
        if($product['contract_type']==DeliveryProductRepository::$strToSignTypeMap['续签']){
            $bindProject[]=['proj_name'=>$product['project_name'],'proj_id'=>$product['project_guid'],'checked'=>true];
            $product['bind_project']=$bindProject;
        }else{
            $product['bind_project']=null;
        }
        return $product;
    }

    /**
     * @param $areaId
     * @return string
     * @throws \yii\base\InvalidConfigException
     */
    private function _getAreaNameByAreaId($areaId)
    {
        $areaName = '';
        if (!empty($areaId)) {
            /** @var ErpBusinessUnitRepository $erpBusinessUnitRepository */
            $erpBusinessUnitRepository = \Yii::createObject(ErpBusinessUnitRepository::className());
            $areaName = $erpBusinessUnitRepository->getBunameByBuguid($areaId);
        }

        return $areaName;
    }

    /**
     * @param $contract_code
     * @return mixed|string
     * @throws \yii\base\InvalidConfigException
     */
    private function _getContractManageAreaIdByContractCode($contract_code)
    {
        $areaId = '';
        if (!empty($contract_code)) {
            /** @var MyscrmContractManageService $myscrmContractManageService */
            $myscrmContractManageService = \Yii::createObject(MyscrmContractManageService::className());
            $contractManage = $myscrmContractManageService->getContractManageByCode($contract_code);
            $areaId = $contractManage->area_id;
        }

        return $areaId;
    }
    /**
     * @param $contract_id
     * @return mixed|string
     * @throws \yii\base\InvalidConfigException
     */
    private function _getContractByContractIdOrErpContractId($contract_id)
    {
        /** @var MyscrmContractManageService $myscrmContractManageService */
        $myscrmContractManageService = \Yii::createObject(MyscrmContractManageService::className());
        return $myscrmContractManageService->getContractByContractIdOrErpContractId($contract_id);
    }
    private function _getContractBySignNumber($signNumber)
    {
        /** @var MyscrmContractManageService $myscrmContractManageService */
        $myscrmContractManageService = \Yii::createObject(MyscrmContractManageService::className());
        return $myscrmContractManageService->getContractBySignNumber($signNumber);
    }
    /**
     * 根据subOrderId获取产品列表
     * @param $orderCode
     * @return array|bool
     */
    public function getAllProducts($subOrderId)
    {
        //获取order
        /** @var DeliverySubOrderRepository $deliverySubOrderRepository */
        $deliverySubOrderRepository=\Yii::createObject(DeliverySubOrderRepository::className());
        /** @var DeliveryProductRepository $deliveryProductRepository */
        $deliveryProductRepository=\Yii::createObject(DeliveryProductRepository::className());
        $subOrder=$deliverySubOrderRepository->findDetailBySubOrderId($subOrderId);
        if(empty($subOrder)){
            return self::setAndReturn(__LINE__,'无法获取出库信息!');
        }
        //获取应用信息并且需要转换成授权时候的id
        $products =  $deliveryProductRepository->findProductsBySubOrderId($subOrderId);

        /** @var ApplicationInfoMappingModel $model */
        $model = \Yii::createObject(ApplicationInfoMappingModel::className());
        $applicationList = $model->getAllAuthApplicationList($products);

        ArrayHelper::multisort($applicationList,'count',SORT_DESC);
        return $applicationList;
    }
}